package com.itheima.datastructure.queue;

import java.util.Iterator;

/**
 * @author tantao
 * @version 1.0
 * @description: 单向环形带哨兵的链表实现队列
 * @date 2025/9/10 13:56
 */
public class LinkedListQueue01<E>
        implements Queue<E>, Iterable<E> {


    /**
     * 链表节点
     *
     * @param <E>
     */
    private static class Node<E> {
        E value;
        Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }


    //头指针/哨兵
    Node<E> head = new Node<>(null, null);
    //尾指针
    Node<E> tail = head;

    //队列大小
    private int size = 0;
    private int capacity = Integer.MAX_VALUE;


    //静静代构
    {
        tail.next = head;
    }

    public LinkedListQueue01() {
    }

    public LinkedListQueue01(int capacity) {
        this.capacity = capacity;

    }

    /**
     * 向队列尾添加
     *
     * @param value 待插入值
     * @return
     */
    @Override
    public boolean offer(E value) {
        if (isFull()) return false;
        //创建新节点,新节点的next->head
        Node<E> added = new Node<>(value, head);
        //尾指针的next指向新节点
        tail.next = added;
        //新节点成为新的尾节点
        tail = added;
        size++;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        Node<E> first = head.next;
        //移除first
        head.next = first.next;
        if (first == tail) {
            //只有一个元素时，头指针和尾指针相等
            tail = head;
        }
        size--;
        return first.value;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return head.next.value;
    }

    @Override
    public boolean isEmpty() {
        //头指针和尾指针相等(均为sentinel)，队列为空,
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return size >= capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p = head.next;

            @Override

            public boolean hasNext() {
                return p != head;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }
}
